<?php
namespace Backend\Models\Sys;

use Backend\Models\Base;

class User extends Base
{

    public function initialize()
    {
        parent::initialize();
    }

    public function getSource()
    {
        return 'sys_user';
    }

    /**
     * 获取系统用户信息的分页数据
     *
     * @param $limit
     * @param $offset
     *
     * @return array|bool
     */
    public function gets($limit, $offset)
    {
        $query = $this->queryBuilder()->columns('*')->from(self::class)->limit($limit, $offset);
        try {
            $result = $query->getQuery()->execute()->toArray();
            if ($result !== false && is_array($result)) {
                $out = [];
                foreach ($result as $k => $v) {
                    unset($v['password']);
                    $out[$k] = $v;
                }
                return $out;
            }
        } catch (\Exception $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function getByAccount($account)
    {
        try {
            $user = $this->db()->query('SELECT * FROM `sys_user` WHERE `account`=:account LIMIT 1', [
                'account' => $account
            ])->fetch();
            if ($user !== false && is_array($user)) {
                return $user;
            }
        } catch (\PDOException $exception) {
            $this->errorLog('SELECT', $this->db()->getSQLStatement(), $exception->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    /**
     * 获取系统用户数据条数
     *
     * @return mixed
     */
    public function getCount()
    {
        $query = $this->select('count(*) AS cnt')->from(self::class);
        try {
            $result = $query->getQuery()->execute()->toArray();
            if ($result !== false && is_array($result) && count($result) > 0) {
                return $result[0]['cnt'];
            }
        } catch (\Exception $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function add($entity)
    {
        try {
            if (isset($entity['password2'])) {
                unset($entity['password2']);
            }
            if ($this->db()->insertAsDict($this->getSource(), $entity)) {
                return $this->db()->lastInsertId();
            }
        } catch (\PDOException $ex) {
            $this->errorLog('INSERT', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function get($uid)
    {
        $query = $this->select('uid,role_id,status')->from(self::class)->where('uid=:uid:', ['uid' => intval($uid)]);
        try {
            $result = $query->getQuery()->execute()->toArray();
            if ($result !== false && is_array($result) && count($result) > 0) {
                return $result[0];
            }
        } catch (\Exception $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function edit($entity)
    {
        try {
            if ($this->db()->updateAsDict($this->getSource(), $entity, sprintf('uid=%d LIMIT 1', intval($entity['uid'])))) {
                return true;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('UPDATE', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function changeStatus($uid)
    {
        $uid  = intval($uid);
        $user = $this->get($uid);
        if ($user === false) {
            return false;
        }
        $entity = [
            'uid'    => $uid,
            'status' => $user['status'] == 1 ? 0 : 1
        ];
        try {
            if ($this->db()->updateAsDict($this->getSource(), $entity, sprintf('uid=%d LIMIT 1', intval($entity['uid'])))) {
                return true;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('UPDATE', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
    }

    public function getUserInfoByUid($uid)
    {
        $query = "SELECT * FROM `sys_user` WHERE `uid`=:uid LIMIT 1";
        try {
            $ret = $this->db()->query($query, ['uid' => $uid])->fetch();
            if ($ret !== false && is_array($ret)) {
                return $ret;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('SELECT', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function resetPassword($entity)
    {
        try {
            if ($this->db()->updateAsDict($this->getSource(), $entity, sprintf('uid=%d LIMIT 1', intval($entity['uid'])))) {
                return true;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('UPDATE', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
    }

}
